package com.zimmur.service.impl;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cglib.reflect.FastClass;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.zimmur.common.ConstData;
import com.zimmur.dao.IVerifyMobileDao;
import com.zimmur.model.account.VerifyMobile;
import com.zimmur.service.IVerifyMobileService;
import com.zimmur.tools.DateUtils;
import com.zimmur.tools.HttpSendSms;
import com.zimmur.tools.RandomUtil;

@Service("verifyMobileService")
public class VerifyMobileServiceImpl implements IVerifyMobileService {
	private Logger log = LoggerFactory.getLogger(VerifyMobileServiceImpl.class);
	
	@Resource  
    private IVerifyMobileDao verifyMobileDao;  	
	
	@Override
	public VerifyMobile getInfoByMobileAndCode(String mobileNo,String code) {
		VerifyMobile verifyMobile = null;
		if(!mobileNo.equals("") && !code.equals("")){
			Map<String, Object> map=new HashMap<String,Object>();
			map.put("mobileNo", mobileNo);
			map.put("verifyCode", code);
			verifyMobile = verifyMobileDao.searchByMobileAndStatus(map);
		}
		return verifyMobile;
	}

	@Override
	public boolean updateVerifyStatus(VerifyMobile verifyMobile) {
		boolean bRet=false;
		int iRet = verifyMobileDao.updateStatusById(verifyMobile);
		if(iRet>0)
			bRet=true;
		
		return bRet;
	}

	@Transactional
	public boolean insertNewVerify(String mobileNo) {
		boolean bRet=false;
		try {
			String randCode = RandomUtil.getDefaultDigitRandom();
			if("".equals(randCode)){
				return false;
			}
			VerifyMobile model = new VerifyMobile();
			model.setMobileno(mobileNo);
			model.setIsverify(0);
			model.setVerifycode(randCode);
			int nowUnixTime = DateUtils.getUnixTimeByDate(DateUtils.getNow());
			int expaireTime = nowUnixTime+(2*60*60);
			model.setSenddate(nowUnixTime);
			model.setExpairedate(expaireTime);		
			int iRet = verifyMobileDao.insert( model);
			if(iRet>0){
				String sendMsg = ConstData.VERIFY_SEND_MESSAGE.replace("%code%", randCode);
				HttpSendSms.sendSms(mobileNo, sendMsg, false);
				bRet=true;
			}	
		} catch (Exception e) {
			log.error(e.getMessage());
		}
		
		return bRet;
	}

}
